package sdfi.lee.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Queue;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import sdfi.lee.Entity.User;
import sdfi.lee.JMS.ConnectionFactory;

public class UserDAO {
	public String register(User user,javax.servlet.http.HttpSession se)
	{
		Session session=null;
		Transaction ts=null;
		try
		{
			
			session=DAO.openSession();
			ts=session.beginTransaction();
			session.save(user);
			ts.commit();
			se.setAttribute("username", user.getUsername());
			se.setAttribute("userid",user.getId());
			se.setAttribute("limit",user.getUstatus());
			return "success";
		}
		catch(Exception ee)
		{
			System.out.println("Exception when user registe ");
			ee.printStackTrace();
			return "error";
		}
		finally
		{
			DAO.closeSession();
		}
		
	}

	public String userexit(javax.servlet.http.HttpSession se)
	{
		try
		{
			
			se.removeAttribute("username");
			se.removeAttribute("userid");
			se.removeAttribute("limit");
			return "success";
		}
		catch(Exception ee)
		{
			System.out.println("Exception when user exit");
			return "error";
		}
	}
	public String login(User user,javax.servlet.http.HttpSession se)
	{
		Session session=null;
		Transaction ts=null;
		try
		{
			List list=null;
			session=DAO.openSession();
			ts=session.beginTransaction();
			Query query=session.createQuery("from User as a where a.username=:username and a.password=:password");
			query.setString("username", user.getUsername());
			query.setString("password", user.getPassword());
			list=query.list();
			ts.commit();
			if(list!=null&&list.size()>0)
			{
					User uer=(User)list.get(0);
					se.setAttribute("username", uer.getUsername());
					se.setAttribute("userid", uer.getId());
					se.setAttribute("limit", uer.getUstatus());
					
			return "success";
			}
			else return "error";
		}
		catch(Exception ee)
		{
			System.out.println("Excepiton when User login");
			ee.printStackTrace();
			return "error";
		}
		finally
		{
			DAO.closeSession();
		}
	}
	public String modify(User user)
	{
		Session session=null;
		Transaction ts=null;
		try
		{
			session=DAO.openSession();
			ts=session.beginTransaction();
			User olduser=(User)session.get(User.class, user.getId());
			olduser.setCompany(user.getCompany());
			olduser.setEmail(user.getEmail());
			olduser.setPassword(user.getPassword());
			olduser.setAddress(user.getAddress());
			olduser.setLinkman(user.getLinkman());
			session.update(olduser);
			ts.commit();
		
			
			return "success";
		}
		catch(Exception ee)
		{
			ts.rollback();
			ee.printStackTrace();
			return "error";
		}
		finally
		{
			DAO.closeSession();
		}
	}
	public User  getUserById(Integer id)
	{
	
		User user=null;
		Session session=null;
		Transaction ts=null;
		try
		{
			session=DAO.openSession();
			ts=session.beginTransaction();
			user=(User)session.get(User.class, id);
			ts.commit();
		
		}
		catch(Exception ee)
		{
			System.out.println("Exception ee when you get uesr ");
			ts.rollback();
			ee.printStackTrace();
		}
		finally
		{
			DAO.closeSession();
		}
		return user;
	}
	public boolean isUserUsed(String name)
	{
		Session session=null;
		Transaction ts=null;
		try
		{
			session=DAO.openSession();
			ts=session.beginTransaction();
			Query query=session.createQuery("select a.username from User as a where a.username=:username");
			int n=query.setParameter("username", name).list().size();
			if(n>0) return false;
			else return true;
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
			return false;
		}
		finally
		{
			DAO.closeSession();
		}
		
	}
	public String addRss(sdfi.lee.Entity.Character mycharacter)throws Exception 
	{
		String sql="insert into mycharacter(userid,rolltype,keyword)value('";
				sql+=mycharacter.getUserid().getId()+"','"+mycharacter.getRolltype().getId()+"','"+mycharacter.getKeyword()+"')";
				Session session=DAO.openSession();
				Connection con=null;
				try
				{
					con=session.connection();
					con.setAutoCommit(false);
					Statement st=con.createStatement();
					String sqlid="select id from mycharacter where userid='"+mycharacter.getUserid().getId()+"' order by id desc";
					int n=st.executeUpdate(sql);
					String id="";
					if(n>0)
					{
					ResultSet rs=st.executeQuery(sqlid);
					rs.next();
					id=new Integer(rs.getInt("id")).toString();
					}
				
					if(this.sendRss(mycharacter.getKeyword(), mycharacter.getRolltype().getTypename()))
					{
						if(n>0) return id;

						else return id;
					}
					else
					{
						con.rollback();
						return "error";
					}
				}
				catch(Exception ee)
				{
					con.rollback();
					ee.printStackTrace();
					return "error";
				}
				finally
				{
					con.commit();
					DAO.closeSession();
				}
	}
	public String userAdd(User user) throws Exception 
	{
		String sql="insert into user(username,password,rgdatetime)value('"
			+user.getUsername()+"','"+user.getPassword()+"','"+user.getDate()+"')";
		Session session=DAO.openSession();
		Connection con=session.connection();
		try
		{
			Statement stm=con.createStatement();
			int n=stm.executeUpdate(sql);
			con.commit();
			if(n>0) return "success";
			else return "error";
		}
		catch(Exception ee)
		{
			System.out.println("Exception ee where admin add user");
			ee.printStackTrace();
			con.rollback();
			return "error";
		}
		
	}
	private boolean sendRss(String keyword,String ne) throws Exception 
	{
		/*
		javax.jms.Connection con=ConnectionFactory.getCon();
		javax.jms.Session se=con.createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
			Queue queue=se.createQueue("search");
		MessageProducer producer=se.createProducer(queue);
		try
		{
	
		MapMessage mapmsg=se.createMapMessage();
		mapmsg.setString("type", "0");
		mapmsg.setString("keyword",keyword);
		producer.send(mapmsg);
		System.out.println("send over");
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
			return false;
		}
		finally
		{
			se.close();
			con.stop();
		}
			*/
		return true;
	
		
	}
	public List<User> getAlluser(int pg,int size)
	{
		List<User> list=null;
		Session session=DAO.openSession();
		Transaction ts=session.beginTransaction();
		try
		{
				Query query=session.createQuery("select " +
						"new sdfi.lee.Entity.User(a.id,a.company,a.linkman,a.username,a.ustatus,a.rgdatetime)" +
						" from User as a");
				query.setMaxResults(size);
				query.setFirstResult((pg-1)*size);
				list=query.list();
				ts.commit();
		}
		catch(Exception ee)
		{
			System.out.println("Exception when you query user information");
			ee.printStackTrace();
			ts.rollback();
			
		}
		finally
		{
			DAO.closeSession();
		}
		return list;
	}
	public String updateUser(String sql)throws Exception 
	{
		int n=0;
		Session session=DAO.openSession();
		Connection con=session.connection();
		Statement stm=con.createStatement();
		n=stm.executeUpdate(sql);
		con.commit();
		if(n>0)
		return "success";
		else return "error";
	}
}
